package com.bsh.pay;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.bsh.api.ApiUtils;
import com.bsh.service.PaymentService;
import com.bsh.utils.Constants;
import com.bsh.utils.MD5;

@Controller
public class WebHookYsbController {
	private static Logger log = LoggerFactory
			.getLogger(WebHookYsbController.class);
	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;
	@Autowired
	HttpSession session;
	@Autowired
	PaymentService paySer;

	@RequestMapping(value = "/pay/v1/ysb/webhook")
	public ModelAndView ysbWebHook() throws Exception {
		response.setContentType("text/html; charset=utf-8");
		JSONObject json = new JSONObject();
		try {
			json.put("result_code", request.getParameter("result_code"));
			json.put("amount", request.getParameter("amount"));
			json.put("result_msg", request.getParameter("result_msg"));
			json.put("orderId", request.getParameter("orderId"));
			json.put("mac", request.getParameter("mac"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (ApiUtils.objIsNotEmpty(json)) {
			log.info("银生宝回调:"+json.toJSONString());
			System.out.println("银生宝回调:"+json.toJSONString());
			// 校验mac值是否相同
			StringBuffer sb = new StringBuffer();
			sb.append("accountId=" + Constants.YSB_MERCHANT_ACCOUNT_ID);
			sb.append("&orderId=" + request.getParameter("orderId"));
			sb.append("&amount=" + request.getParameter("amount"));
			sb.append("&result_code=" + request.getParameter("result_code"));
			sb.append("&result_msg=" + request.getParameter("result_msg"));
			sb.append("&key=" + Constants.YSB_KEY);
			String localMac=MD5.GetMD5Code(sb.toString());
			localMac=localMac.toUpperCase();
			//校验成功
			if (localMac.equals(request.getParameter("mac"))) {
				// 进service
				Integer res = paySer.backYsbPayment(json);
				if (res > 0) {
					response.getWriter().println("success");
				} else {
					log.error("webHook_error:回调结果fail,业务回滚");
					response.getWriter().println("fail");
				}
			}else{
				log.error("webHook_error:回调结果fail,验签失败");
				response.getWriter().println("fail");
			}
		}
		response.getWriter().println("Thanks");
		return null;
	}
}
